package danran.dbapi.controller.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;

/**
 * @Classname JwtUtil
 * @Description TODO
 * @Date 2022/1/17 12:48
 * @Created by RanCoder
 */
public class JwtUtil {

    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    public static String createToken(String userId, String secret) {
        Calendar now = Calendar.getInstance();
//        now.add(Calendar.MINUTE, 30);
        now.add(Calendar.MONTH, 1);
        Date expireTime = now.getTime();
        return JWT.create().withAudience(userId)// token签发对象
                .withIssuedAt(new Date())// token签发时间
                .withExpiresAt(expireTime)// 有效时间
                .sign(Algorithm.HMAC256(secret));// 加密
    }

    /**
     * 校验Token的有效性
     *
     * @param token  token string
     * @param secret userId
     */
    public static boolean verifyToken(String token, String secret) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            log.warn("Token 校验失败，因为 ：{}", e.getMessage());
            return false;
        }
    }

    /**
     * 获取签发的对象
     *
     * @param token
     * @return
     */
    public static String getAudience(String token) {
        return JWT.decode(token).getAudience().get(0);
    }


}
